#Touhou Diablo g2m parser

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class touhouDiablo_g2m(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(touhouDiablo_g2m,self).__init__("G2M")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def parse_materials(self, matNum):
        
        line = self.inFile.readline().split()
        matName = line[0][1:-1]
        texName = line[1][1:-1]
        
        self.create_material(matNum)
        self.add_material_name(matNum, matName)
        self.add_texture_name(matNum, texName)
        return matName
        
    def parse_vertices(self, meshName):
        
        numVerts = int(self.inFile.readline().strip())
        for i in range(numVerts):
            line = self.inFile.readline().split()
            
            vx, vz, vy = line[0:3]
            tu, tv = line[3:5]
            nx, ny, nz = line[5:8]
            
            tv = float(tv) * -1
            
            self.create_vertex(meshName, i)
            self.add_coords(meshName, i, [vx, vy, vz])
            self.add_uv(meshName, i, [tu, tv])
                
    def parse_faces(self, meshName):
        
        numFaces = int(self.inFile.readline().strip())
        for i in range(numFaces):
            line = self.inFile.readline().split()
            
            v1, v2, v3 = line[0:3]
            self.create_face(meshName, i)
            self.add_face_verts(meshName, i, [v1, v2, v3])
            self.add_face_material(meshName, i, 0)
        
    def parse_file(self):
        '''Main parser method. Can be replaced'''
        
        #armature
        line = self.inFile.readline().strip()
        
        numMesh = int(self.inFile.readline().strip())
        for i in range(numMesh):
            meshName = self.parse_materials(i)      
            self.create_object(meshName)
            self.parse_vertices(meshName)
            self.parse_faces(meshName)
        
def read_file(path):
    '''Read the file'''
    
    openFile = open(path, 'r')
    obj = touhouDiablo_g2m(inFile=openFile)
    obj.parse_file()
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "", "G2M", "Touhou Diablo G2M"

if __name__ == '__main__':
    
    file1 = "body.g2m"
    file2 = "f1.g2m"
    obj = read_file(file2)